import React from 'react';
import {connect} from 'react-redux'
import {Button, message, Form, Input, Switch, DatePicker, Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;
import {messages} from "share/common";
import LanguageInput from "components/template/language-input/language-input";
import moment from "moment";
import ListSelector from "components/list-selector";
import vendorService from 'containers/supplier-maintenance/vendorService';
import CustomerInfoMaintenanceService from 'containers/customer-info-maintenance/customer-info-maintenance.service'

let deepRecord = {
  venderTypeId: "",
  venderCode: "",
  venNickname: "",
  effectiveDate: null,
  _venType: true,
  artificialPerson: "",
  taxIdNumber: "",
  contact: "",
  contactPhone: "",
  contactMail: "",
  fax: "",
  address: "",
  notes: "",
  companyOid: "",
  companyName: "",
};
let otherInfoInput = [
  {key: "artificialPerson", name: messages('financial-management.key329'/*法人代表*/), value: ""},
  {key: "taxIdNumber", name: messages('financial-management.key330'/*税务登记号*/), value: ""},
  {key: "contact", name: messages('financial-management.key331'/*联系人*/), value: ""},
  {key: "contactPhone", name: messages('financial-management.key332'/*联系人电话*/), value: ""},
  {key: "contactMail", name: messages('financial-management.key333'/*邮箱*/), value: ""},
  {key: "fax", name: messages('financial-management.key334'/*传真*/), value: ""},
];
class NewSupplierInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tenant: window.location.href.indexOf('tenant') !== -1,
      loading: false,
      data: [],
      confirmLoading: false,
      record: JSON.parse(JSON.stringify(deepRecord)),
      languageKey: 0,
      showListSelector: false,
      showCompanyListSelector: false,
      companys: [],
    }
  }


  componentWillMount() {
    this.getCompanys();
  }

  componentWillReceiveProps(nextProps) {
    const {languageKey} = this.state;
    if (nextProps.params.visible !== this.props.params.visible && nextProps.params.visible) {
      if (nextProps.params.id) {
        this.getSupplierDetail(nextProps.params.id);
      } else {
        this.props.form.setFieldsValue(deepRecord);
        this.setState({
          languageKey: languageKey + 1,
          record: JSON.parse(JSON.stringify(deepRecord)),
        });
      }
    }
    this.setState({
      tenant: window.location.href.indexOf('tenant') !== -1,
    });
  }

  //获取客户详情
  getSupplierDetail = (id) => {
    const {languageKey, tenant} = this.state;
    this.setState({
      loading: true,
    });
    vendorService.getVendorInfoById(id, tenant ? "?roleType=TENANT" : "")
      .then(res => {
        if (res.data.effectiveDate) {
          res.data.effectiveDate = moment(moment(res.data.effectiveDate).utc().format())
        }
        res.data._venType = res.data.venType === 1001;
        this.props.form.setFieldsValue(res.data);
        this.setState({
          loading: false,
          record: res.data,
          languageKey: languageKey + 1,
        });
      })
      .catch(err => {
        this.setState({
          loading: false,
        });
      })
  };

  onOk = () => {
    const {record, tenant} = this.state;
    const {user} = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if(!record.venderTypeId){
          message.error(messages('supplier-maintenance.key1')/*供应商类型不能为空*/);
          return;
        }
        let params = Object.assign(record, values);
        params.employeeID = user.employeeID;
        params.venOperatorNumber = user.employeeID;
        params.venOperatorName = user.fullName;
        params.venType = values._venType ? 1001 : 1002;
        params.effectiveDate = params.effectiveDate ? params.effectiveDate.utc().format() : null;
        params.source = tenant ? "TENANT" : "COMPANY";
        this.setState({
          confirmLoading: true,
        });
        if (record.id) {
          this.editSupplierType(params);
        } else {
          this.addSupplierType(params);
        }
      }
    });
  };

  addSupplierType = (params) => {
    const {tenant} = this.state;
    vendorService.addVendorInfo(params, tenant ? "?roleType=TENANT" : "").then(response => {
      if (response.data.msg === '成功' || response.data.code === '0000') {
        this.props.close();
        message.success(`${messages("common.save.success", {name: ""})}`);
      } else {
        message.error(`${messages("common.save.filed")}, ${response.data.msg}`);
      }
        this.setState({confirmLoading: false});
      }
    ).catch(e => {
      message.error(`${messages("common.save.filed")}, ${e.response.data.message}`);
      this.setState({
        confirmLoading: false,
      });
    })
  };

  editSupplierType = (params) => {
    const {tenant} = this.state;
    vendorService.updateVendorInfo(params, tenant ? "?roleType=TENANT" : "").then(response => {
      if (response.data.msg === '成功' || response.data.code === '0000') {
        this.props.close();
        message.success(`${messages("common.operate.success")}`);
      } else {
        message.error(`${messages("common.operate.filed")}, ${response.data.msg}`);
      }
        this.setState({confirmLoading: false});
      }
    ).catch(err => {
      message.error(`${messages("common.operate.filed")}, ${e.response.data.message}`);
      this.setState({
        confirmLoading: false,
      });
    })
  };

  onCancel = () => {
    this.props.close();
  };

  renderFormItem = (arr) => {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    const {record} = this.state;
    return (
      arr.map(item => {
        return (
          <FormItem label={item.name} {...formItemLayout} key={item.key}>
            {getFieldDecorator(item.key, {
              initialValue: record[item.key],
            })(
              <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
          </FormItem>
        )
      }))
  };

  i18nChange = (name, i18nName) => {
    const record = this.state.record;
    record.venNickname = name;
    if (!record.i18n) {
      record.i18n = {};
    }
    record.i18n.venNickname = i18nName;
  };

  //切换客户类型
  handleChangeSupplierType = (result) => {
    const {record} = this.state;
    if (result.result.length) {
      record.venderTypeId = result.result[0].id;
      record.venderTypeName = result.result[0].name;
      this.setState({
        record,
      });
    }
    this.setState({
      showListSelector: false,
    });
  };

  changeListSelector = (e, bool) => {
    this.setState({
      showListSelector: bool,
    });
  };

  //所属公司可选项
  getCompanys = () => {
    CustomerInfoMaintenanceService.getCompanys("supplier-maintain")
      .then(res => {
          this.setState({
            companys: res.data,
          });
        }
      ).catch(err => {

    })
  };

  render() {
    const {record, confirmLoading, languageKey, showListSelector, tenant, companys} = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 16}
    };
    return (
      <div>
        <Form>
          <div className="other-icon"/>
          <div>{messages('common.baseInfo')/*基本信息*/}</div>
          <FormItem label={messages('common.column.status'/*状态*/)}{...formItemLayout}>
            {getFieldDecorator('_venType', {
              valuePropName: "checked",
            })(
              <Switch/>
            )}
          </FormItem>
          <FormItem label={<span><span style={{color: 'red'}}>*</span>&nbsp;{messages('financial-management.key325'/*供应商类型*/)}</span>}{...formItemLayout}>
            <div style={{width: "100%"}} onClick={(e) =>this.changeListSelector(e,true)}>
              <Input placeholder={messages('common.please.select')/* 请选择 */}
                     value={record.venderTypeName}
                     key={languageKey}/>
            </div>
          </FormItem>
          {
            !tenant &&
            <FormItem {...formItemLayout} label={messages('customer-info-maintenance.key18')/*所属公司*/}>
              {getFieldDecorator('companyOid', {
                rules: [{
                  required: true,
                  message: messages('customer-info-maintenance.key19')/*所属公司不能为空*/
                }]
              })(
                <Select
                  disabled={!!record.id}
                  showSearch={true}
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  placeholder={messages('common.please.enter')}>
                  {
                    companys.map(item => {
                      return (
                        <Option key={item.companyOID} value={item.companyOID}>{item.name}</Option>
                      )
                    })
                  }
                </Select>
              )}
            </FormItem>
          }
          <FormItem label={messages('financial-management.key326'/*供应商代码*/)} {...formItemLayout}>
            {getFieldDecorator('venderCode', {
              rules: [{
                required: true,
                message: messages('common.please.enter')  //请输入
              }]
            })(
              <Input placeholder={messages('common.please.enter')/* 请输入 */} disabled={!!record.id}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-management.key327'/*供应商名称*/)} {...formItemLayout}>
            {getFieldDecorator('venNickname', {
              rules: [{
                required: true,
                message: messages('common.please.enter')  //请输入
              }]
            })(
              <LanguageInput key={languageKey}
                             name={record.venNickname}
                             i18nName={record.i18n && record.i18n.venNickname ? record.i18n.venNickname : null}
                             isEdit={record.id}
                             nameChange={this.i18nChange}/>)}
          </FormItem>
          <FormItem label={messages('customer-info-maintenance.key21')} {...formItemLayout}>
            {getFieldDecorator('effectiveDate', {
            })(
              <DatePicker format="YYYY-MM-DD"/>
            )}
          </FormItem>
          <div className="other-icon"/>
          <div>{messages('customer-info-maintenance.key22')/*其他信息*/}</div>
          {this.renderFormItem(otherInfoInput)}
          <FormItem label={messages('financial-management.key335'/*地址*/)} {...formItemLayout}>
            {getFieldDecorator('address', {
            })(
              <TextArea placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
          </FormItem>
          <FormItem label={messages('financial-management.key322'/*备注*/)} {...formItemLayout}>
            {getFieldDecorator('notes', {
            })(
              <TextArea placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" onClick={this.onOk} loading={confirmLoading}>
              {messages('common.save')}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')}
            </Button>
          </div>
        </Form>
        <ListSelector
          visible={showListSelector}
          type="vendor_type"
          selectedData={[record.venderTypeId]}
          onOk={this.handleChangeSupplierType}
          onCancel={(e) =>this.changeListSelector(e, false)}
          single
          extraParams={{isEnabled: true}}
        />
      </div>
    )
  }
}


NewSupplierInfo.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}

const wrappedNewSupplierInfo2 = Form.create()(NewSupplierInfo);
export default connect(mapStateToProps)(wrappedNewSupplierInfo2);
